﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using OpenPhotoAlbum.Controls;

namespace OpenPhotoAlbum
{
    public partial class PasswordRecovery : AlbumPage
    {
        private DbAccess.RecoveringRequest _request;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

			this.Title = StringUtility.AddAppPrefix(Resources.Strings.Title_PasswordRecovery);

            _request = BusinessLogics.RecoveringRequestManager.Instance.GetRequest(UrlContext.Key);
            if (_request == null) { throw new InvalidKeyException(); }
            if (_request.Used) { throw new UsedKeyException(); }

            ltrNewPassword.Text = StringUtility.AddColon(Resources.Strings.Login_NewPassword);
            
            btnSubmit.Text = Resources.Strings.Submit;

            btnSubmit.Click += new EventHandler(btnSubmit_Click);
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (_request == null || string.IsNullOrEmpty(tbNewPassword.Text)) { return; }

            DbAccess.DbLinqClassesDataContext context = new DbAccess.DbLinqClassesDataContext();
            BusinessLogics.UserManager.Instance.ChangePassword(context, _request.RecoveringUserId, tbNewPassword.Text);
            BusinessLogics.RecoveringRequestManager.Instance.SetKeyUsed(context, _request.RecoveringKey);
            context.SubmitChanges();

			JsMsgBox.Show(this, Resources.Strings.NewPasswordSaved, Links.Login);
        }

		protected override void AppendSiteMapNodes(AlbumSiteMapProvider provider)
		{
			base.AppendSiteMapNodes(provider);

			provider.AppendSiteMapNode(Resources.Strings.SC_Home, Links.Default);
			provider.AppendSiteMapNode(Resources.Strings.PasswordRecovery, RawUrl);
		}
    }

    public class InvalidKeyException : Exception { }

    public class UsedKeyException : Exception { }
}
